package cn.edu.hnpu.news.ui;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import cn.edu.hnpu.news.R;

public class KuaidiActivity extends BaseActivity {
    private static final String APP_CACAHE_DIRNAME = "/webcache";
    private WebView webView;
    private String loadUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kuaidi);
        loadUrl = getIntent().getStringExtra("detailUrl");
        webView = (WebView) findViewById(R.id.webView);
        initWebView();
        // 设置WebViewClient
        webView.setWebViewClient(new WebViewClient() {
            // 这个方法在用户试图点开页面上的某个链接时被调用
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("http") || url.startsWith("https")) {
                    return false;
                } else {
                    if (url.equals("test://back")) {
                        finish();
                        return true;
                    } else {
                        return false;
                    }
                }
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                /**
                 * 去除加载页面的底部广告
                 */
                view.loadUrl("javascript:function setTop(){document.querySelector('#result > div:nth-child(3)').style.display=\"none\";}setTop();");
            }

            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
            }
        });
        webView.loadUrl(loadUrl);


    }

    private void initWebView() {

        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); // 设置缓存模式
        // 开启 DOM storage API 功能
        webView.getSettings().setDomStorageEnabled(true);
        // 开启 database storage API 功能
        webView.getSettings().setDatabaseEnabled(true);
        String cacheDirPath = getFilesDir().getAbsolutePath()
                + APP_CACAHE_DIRNAME;
        // 设置数据库缓存路径
        webView.getSettings().setDatabasePath(cacheDirPath);
        // 设置 Application Caches 缓存目录
        webView.getSettings().setAppCachePath(cacheDirPath);
        // 开启 Application Caches 功能
        webView.getSettings().setAppCacheEnabled(true);
    }

}
